<template>
	<view>
		<u-picker ref="picker" :columns="addressList" :loading="loading" keyName="name" @change="change" :show="show"
			@cancel="show = false" @confirm="confirm">
		</u-picker>
	</view>
</template>
<script setup>
	import {
		ref,
		watch,
		computed,
		nextTick
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app';
	import cityData from "@/config/regions.json"


	const show = defineModel()
	const props = defineProps({
		defaultValue: {
			default: [3442, 1, 2],
			type: Array
		}
	})
	const emits = defineEmits(['confirmCityPicker'])
	const loading = ref(true)
	const provinces = ref([])
	const citys = ref([])
	const areas = ref([])
	const pickerValue = ref([0, 0, 0])
	const defaultValue = ref([3442, 1, 2])
	const picker = ref(null)
	const addressList = computed(() => {
		return [provinces.value, citys.value, areas.value];
	})
	const handlePickValueDefault = () => {
		// 设置省
		pickerValue.value[0] = provinces.value.findIndex(item => Number(item.id) === defaultValue.value[0]);
		// 设置市
		citys.value = provinces.value[pickerValue.value[0]]?.children || [];
		pickerValue.value[1] = citys.value.findIndex(item => Number(item.id) === defaultValue.value[1]);
		// 设置区
		areas.value = citys.value[pickerValue.value[1]]?.children || [];
		pickerValue.value[2] = areas.value.findIndex(item => Number(item.id) === defaultValue.value[2]);
		// 重置下位置
		picker.value.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]], true);
	}
	const getData = () => {
		provinces.value = cityData.sort((left, right) => (Number(left.code) > Number(right
			.code) ? 1 : -1));
		nextTick(() => {
			handlePickValueDefault()
			loading.value = false
		})
	}
	onShow(() => {
		getData();
	})


	const change = (e) => {
		if (loading.value) return;
		const {
			columnIndex,
			index,
			indexs
		} = e
		// 改变了省
		if (columnIndex === 0) {
			citys.value = provinces.value[index]?.children || []
			areas.value = citys.value[0]?.children || []
			picker.value.setIndexs([index, 0, 0], true)
		} else if (columnIndex === 1) {
			areas.value = citys.value[index]?.children || []
			picker.value.setIndexs(indexs, true)
		}
	}

	const confirm = (e) => {
		emits('confirmCityPicker', e.value)

	}
</script>